package com.qianyu.project.core.scan;

import cn.hutool.core.util.ClassUtil;
import com.qianyu.project.core.annotation.FlowHandler;
import com.qianyu.project.core.context.handler.FlowHandlerFactory;
import com.qianyu.project.core.utils.FlowHandlerValidation;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Set;

/**
 * @author gs
 * @date create in 2021/1/22 7:54
 */
@Data
public class PackageScan {

    private FlowHandlerFactory flowHandlerFactory;
    private String[] packages;

    public PackageScan(FlowHandlerFactory flowHandlerFactory, String packages) {
        this.flowHandlerFactory = flowHandlerFactory;
        this.packages = packages.split(",");

        //遍历扫描指定的所有包
        for (String packageName : this.packages){
            Set<Class<?>> classes = ClassUtil.scanPackage(packageName);
            classes.iterator().forEachRemaining(type -> {
                //拿到注解判断是否有注解标识
                FlowHandler flowHandler = (FlowHandler) type.getAnnotation(FlowHandler.class);
                if (flowHandler != null) {
                    if(type.isAnnotationPresent(Component.class)) {
                        if (FlowHandlerValidation.isImplements(type)) {
                            //拿到要做后置处理的表名
                            String target = flowHandler.value();
                            this.flowHandlerFactory.pushHandler(target, type);
                        }
                    }
                }
            });
        }
    }
}
